import {
  PlusOutlined,
  DeleteOutlined,
  CloudDownloadOutlined,
  CloudUploadOutlined,
  SyncOutlined,
  EditOutlined,
  CodeOutlined,
  DownOutlined,
  SettingOutlined,
  FilePdfOutlined,
} from '@ant-design/icons';
import { Button, DatePicker, Dropdown, Popconfirm, message } from 'antd';
import React, { useState, useRef } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import type { Pagination } from '@/services/types';
import type { DatasourceItem } from '@/services/develop/types';
import { ProFormText, ProFormTextArea } from '@ant-design/pro-form';
import EditForm from '@/components/EditForm';
import { DatasourceColumns } from './columns';
import { handleAdd, handleUpdate, handleRemove, handleSync } from './action';
import { pageDatasource } from '@/services/develop/datasource';
import DictSelect from '@/components/DictSelect';
import { ProConfigProvider } from '@ant-design/pro-components';
import SzhomeTable from '@/components/Custom/SzhomeTable';

const Datasource: React.FC = () => {
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<DatasourceItem>();
  const [selectedRowsState, setSelectedRows] = useState<DatasourceItem[]>([]);

  const columns: ProColumns<DatasourceItem>[] = [
    ...DatasourceColumns,
    {
      title: '操作',
      align: 'center',
      valueType: 'option',
      width: 220,
      render: (_, record) => [
        <a
          key={'edit-' + record.id}
          onClick={() => {
            setCurrentRow(record);
            handleModalVisible(true);
          }}
        >
          <EditOutlined />
          编辑
        </a>,

        <Popconfirm
          key={'sync-' + record.id}
          title="您确定要同步此数据源吗？"
          onConfirm={async () => {
            await handleSync([record]);
            actionRef.current?.reloadAndRest?.();
          }}
          okText="Yes"
          cancelText="No"
        >
          <a key={'sync-' + record.id}>
            <SyncOutlined />
            同步
          </a>
        </Popconfirm>,

        <Dropdown
          key="more"
          menu={{
            items: [
              {
                key: 'excel',
                label: 'Excel文档',
                icon: <FilePdfOutlined />,
                onClick() {
                  window.location.href =
                    '/api/szhome-develop/develop/datasource/excel/' + record.id;
                },
              },
              {
                key: 'pdf',
                label: 'Pdf文档',
                icon: <FilePdfOutlined />,
              },
              {
                key: 'html',
                label: 'HTML文档',
                icon: <FilePdfOutlined />,
              },
              {
                key: 'sql',
                label: '建表脚本',
                icon: <FilePdfOutlined />,
              },
              {
                type: 'divider',
              },
              {
                key: 'delete',
                label: (
                  <Popconfirm
                    key={'delete-' + record.id}
                    title="您确定要删除此数据源吗？"
                    onConfirm={async () => {
                      await handleRemove([record]);
                      setSelectedRows([]);
                      actionRef.current?.reloadAndRest?.();
                    }}
                    okText="Yes"
                    cancelText="No"
                  >
                    删除
                  </Popconfirm>
                ),
                icon: <DeleteOutlined />,
                danger: true,
              },
            ],
          }}
        >
          <a>
            更多 <DownOutlined />
          </a>
        </Dropdown>,
      ],
    },
  ];

  return (
    <ProConfigProvider
      valueTypeMap={{
        link: {
          render: (text) => <a>{text}</a>,
          renderFormItem: (text, props) => (
            <DatePicker initialValue="hello, world" placeholder={'test'} {...props?.fieldProps} />
          ),
        },
      }}
      hashed={false}
    >
      <PageContainer>
        <SzhomeTable<DatasourceItem, Pagination>
          actionRef={actionRef}
          request={pageDatasource}
          columns={columns}
          toolBarRender={() => [
            <Button
              type="primary"
              key="primary"
              onClick={() => {
                setCurrentRow(undefined);
                handleModalVisible(true);
              }}
            >
              <PlusOutlined /> 新增
            </Button>,

            <Popconfirm
              key="batch_sync"
              disabled={selectedRowsState?.length == 0}
              title={
                <>
                  <span>您确定要同步已选</span>
                  {selectedRowsState?.length} <span>条数据源数据吗？</span>
                  <br />
                  <span>如果数据源中表和字段数量较大，同步操作可能需要一段时间才能完成。</span>
                </>
              }
              onConfirm={async () => {
                await handleSync(selectedRowsState);
                actionRef.current?.reloadAndRest?.();
              }}
              okText="Yes"
              cancelText="No"
            >
              <Button key="batch_sync" disabled={selectedRowsState?.length == 0}>
                <SyncOutlined />
                同步
              </Button>
            </Popconfirm>,

            <Popconfirm
              key={'batch_remove'}
              disabled={selectedRowsState?.length == 0}
              title={'您确定要删除已选' + selectedRowsState?.length + '条数据源数据吗？'}
              onConfirm={async () => {
                await handleRemove(selectedRowsState);
                setSelectedRows([]);
                actionRef.current?.reloadAndRest?.();
              }}
              okText="Yes"
              cancelText="No"
            >
              <Button key="batch_remove" danger disabled={selectedRowsState?.length == 0}>
                <DeleteOutlined />
                删除
              </Button>
            </Popconfirm>,

            <Button
              key="primary"
              onClick={() => {
                handleModalVisible(true);
              }}
            >
              <CloudDownloadOutlined /> 导出
            </Button>,

            <Button
              key="primary"
              onClick={() => {
                handleModalVisible(true);
              }}
            >
              <CloudUploadOutlined /> 导入
            </Button>,
          ]}
          rowSelection={{
            onChange: (_, selectedRows) => {
              setSelectedRows(selectedRows);
            },
          }}
        />

        <EditForm
          visible={createModalVisible}
          name="数据源"
          model={currentRow || { id: undefined }}
          onAdd={handleAdd}
          onUpdate={handleUpdate}
          afterEdit={() => {
            setCurrentRow(undefined);

            if (actionRef.current) {
              actionRef.current.reload();
            }
          }}
          onCancel={handleModalVisible}
        >
          <ProFormText name="id" hidden={true} />
          <DictSelect label="类型" name="type" dict="database.type" cols={24} />
          <ProFormText label="名称" name="name" colProps={{ xs: 12 }} />
          <ProFormText label="表前缀" name="tablePrefix" colProps={{ xs: 12 }} />
          <ProFormText
            required
            label="连接地址"
            name="url"
            placeholder={'形如jdbc:mysql://localhost:3306/db'}
            colProps={{ xs: 24 }}
          />
          <ProFormText required label="用户名" name="username" colProps={{ xs: 12 }} />
          <ProFormText.Password required label="密码" name="password" colProps={{ xs: 12 }} />
          <ProFormTextArea label="备注" name="remark" colProps={{ xs: 24 }} />
        </EditForm>
      </PageContainer>
    </ProConfigProvider>
  );
};

export default Datasource;
